from decimal import Decimal

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.filters import OrderingFilter
from rest_framework.generics import CreateAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from books.models import Books
from orders.models import OrderInfo, OrderBooks
from orders.serializers import OrderSettlementSerializer, SaveOrderSerializer, OrderListSerializers, \
    OrderUncommentedSerializer
from utils import pagination


class OrderSettlementView(APIView):
    """订单结算"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """获取"""
        user = request.user

        # 从收藏中获取用户勾选要结算的商品信息
        redis_conn = get_redis_connection('collect')
        redis_collect = redis_conn.hgetall('collect_%s' % user.id)
        collect_selected = redis_conn.smembers('collect_selected_%s' % user.id)

        collect = {}
        for book_id in collect_selected:
            collect[int(book_id)] = int(redis_collect[book_id])

        # 查询商品信息
        books = Books.objects.filter(id__in=collect.keys())
        for book in books:
            book.duration = collect[book.id]

        # 运费
        freight = Decimal('10.00')

        serializer = OrderSettlementSerializer({'freight': freight, 'books': books})
        return Response(serializer.data)


class SaveOrderView(CreateAPIView):
    """
    保存订单
    """
    permission_classes = [IsAuthenticated]
    serializer_class = SaveOrderSerializer


class OrderListView(ListAPIView):
    """展示订单列表页"""
    serializer_class = OrderListSerializers
    # pagination_class = pagination  # 分页属性
    # filter_backends = [OrderingFilter]  # 过滤排序属性
    # ordering_fields = ('order_id')

    def get_queryset(self):
        # user = self.request.user
        # id = user.id
        return OrderInfo.objects.filter(user_id=self.request.user.id)

class OrderReceivedView(APIView):
    """已收件"""
    def get(self, request, order_id):
        """修改账单属性为已收货"""
        # 验证用户
        user = request.user
        OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNRECEIVED']).update(
            status=OrderInfo.ORDER_STATUS_ENUM["RECEIVED"])
        return Response({'username': user.username})


class OrderUncommentedView(APIView):
    def get(self,request,pk):
        # 获取用户信息
        user = request.user
        # 如果用户登录
        if user:
            # 获取未评论订单对象查询集
            uncomment_orders = OrderBooks.objects.filter(order_id=pk,is_commented=0)
            # 遍历未评论订单对象查询集
            print(uncomment_orders)
            for uncomment in uncomment_orders:
                # 获取订单商品的id
                books_id = uncomment.book_id
                # 获取订单商品对象
                books = Books.objects.get(id=books_id)
                # 将订单商品对象付给订单对象
                uncomment.book = books
            print(uncomment_orders)
            # 序列化返回订单对象
            ser = OrderUncommentedSerializer(uncomment_orders,many=True)
            # 返回响应
            return Response(ser.data)

class CommentSaveView(APIView):
    """实现保存订单"""

    def post(self,request, order_id):
        """
        保存订单商品的评论信息
        :param request:
        :param order_id:
        :return:
        """
        # 1.获取请求体数据
        print(self.request.data)
        order_id = self.request.data["order"]
        book_id = self.request.data["book"]
        comment = self.request.data["comment"]
        score = self.request.data["score"]
        is_anonymous = self.request.data["is_anonymous"]

        # 3.获取订单商品对象
        ordersku = OrderBooks.objects.filter(order_id=order_id, book_id=book_id)[0]
        comment_info = {"comment":comment,
                        "score":score,
                        "is_anonymous":is_anonymous,
                        "is_commented":True}

        ordersku.__dict__.update(**comment_info)
        ordersku.save()

        return Response({"massage": "OK"})

